<?php

declare(strict_types=1);

namespace SixShop\Wangdian\Config;

/**
 * Configuration class for the Wangdian SDK
 */
readonly class Config
{
    public const SANDBOX_BASE_URL = 'https://sandbox.wangdian.cn/openapi2';
    public const PRODUCTION_BASE_URL = 'https://api.wangdian.cn/openapi2';

    public function __construct(
        public string $sid,
        public string $appKey,
        public string $appSecret,
        public string $baseUrl = self::SANDBOX_BASE_URL,
        public int $timeout = 30,
        public bool $debug = false,
        public ?string $logFile = null,
    ) {
        $this->validate();
    }

    /**
     * Create a configuration for sandbox environment
     */
    public static function sandbox(string $sid, string $appKey, string $appSecret): self
    {
        return new self(
            sid: $sid,
            appKey: $appKey,
            appSecret: $appSecret,
            baseUrl: self::SANDBOX_BASE_URL,
            debug: true
        );
    }

    /**
     * Create a configuration for production environment
     */
    public static function production(string $sid, string $appKey, string $appSecret): self
    {
        return new self(
            sid: $sid,
            appKey: $appKey,
            appSecret: $appSecret,
            baseUrl: self::PRODUCTION_BASE_URL,
            debug: false
        );
    }

    /**
     * Get full API endpoint URL
     */
    public function getEndpoint(string $api): string
    {
        return rtrim($this->baseUrl, '/') . '/' . ltrim($api, '/');
    }

    /**
     * Check if running in sandbox mode
     */
    public function isSandbox(): bool
    {
        return str_contains($this->baseUrl, 'sandbox');
    }

    /**
     * Validate configuration parameters
     */
    private function validate(): void
    {
        if (empty($this->sid)) {
            throw new \InvalidArgumentException('SID cannot be empty');
        }

        if (empty($this->appKey)) {
            throw new \InvalidArgumentException('App Key cannot be empty');
        }

        if (empty($this->appSecret)) {
            throw new \InvalidArgumentException('App Secret cannot be empty');
        }

        if ($this->timeout <= 0) {
            throw new \InvalidArgumentException('Timeout must be greater than 0');
        }

        if (!filter_var($this->baseUrl, FILTER_VALIDATE_URL)) {
            throw new \InvalidArgumentException('Invalid base URL');
        }
    }
}